package com.servlet.album;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.service.AlbumService;
import com.util.DBUtil;
import com.util.Log;
import com.view_object.UserVO;
import lombok.SneakyThrows;
import sun.rmi.server.InactiveGroupException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yuisama
 * @date 2023/03/11 15:34
 **/

@WebServlet("/studio/album/add.do")
//此处写要跳转的do操作
public class AddJsonServlet extends HttpServlet {
//    private final AlbumService albumService = new AlbumService();
//    private  final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    @SneakyThrows
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null) {
            throw new RuntimeException("用户未登录");
        }
        UserVO currentUser = (UserVO) session.getAttribute("currentUser");
        if(currentUser == null){
            throw new RuntimeException("用户未登录");
        }
        req.setCharacterEncoding("utf-8");
        int aid = Integer.parseInt(req.getParameter("aid"));
        String[] tidArray = req.getParameterValues("add-tid");
        //getParameter 和 getParameterValues有什么区别呢
        //传入 tid=1&tid=2&tid=3
        //getParameter只能得到第一个， getParameterValues会得到全部信息
        List<Integer> tidList = Arrays.stream(tidArray).map(Integer::parseInt).collect(Collectors.toList());
        //Arrays.stream()将一个数组转化成一个流，支持并行操作数据，提高程序的性能
        //Integer类的方法 parseInt
        //Collectors.toList() 用来结束Stream流


        String sqlFormat = "insert into relations (aid,tid) values %s";
        String collect = tidList.stream().map(tid -> String.format("(%d,%d)", aid, tid)).collect(Collectors.joining(", "));
        //直接就可以Join出来我们需要的
        String sql = String.format(sqlFormat,collect);
        //第一次执行，参数写成了为填充之前的
        Log.println("执行SQL:"+ sql);


       try(Connection c = DBUtil.connection()){
           try(PreparedStatement ps = c.prepareStatement(sql)){
               ps.executeUpdate();
           }
       }

//        Object view = albumService.getBindInfo(currentUser,aid);
//
//        String json = objectMapper.writeValueAsString(view);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/type");
      //  resp.getWriter().print(json);
        PrintWriter writer = resp.getWriter();
        writer.println("添加成功");
    }
}

